//服务器地址
var imgUrl = 'http://192.168.1.105/';
// var serverUrl = 'http://192.168.3.19/thinkphp/public/index.php/index/';
var serverUrl = 'http://www.china-spin.com/thinkphp/public/index.php/index/';
//var serverUrl = 'http://zhongfang.sujianxun.com/thinkphp/public/index.php/index/';

//重新获取缓存
function getStorageAll() {
    user_id = $api.getStorage('user_id');
    isCompany_user = $api.getStorage('vcompany');
    group_id = $api.getStorage('group_id');
    user_name = $api.getStorage('user_name');
    // nick_name = $api.getStorage('company');
    nick_name = $api.getStorage('nickname');
    head_pic = $api.getStorage('head_pic');
    company_name = $api.getStorage('company');
    birthday = $api.getStorage('birthday');
    sex = $api.getStorage('sex');
    avatar = $api.getStorage('avatar');
    lat = $api.getStorage('lat');
    lon = $api.getStorage('lon');
    rongcloud_token = $api.getStorage('rongcloud_token');
}

//重新登录监听
function sendReGetMyInfo() {
    api.sendEvent({
        name: 'reGetMyInfo',
        extra: {
            key: 'true'
        }
    });
}

//两次退出
var first = null;
function back() {
    api.addEventListener({
        name: 'keyback'
    }, function (ret, err) {
        if (!first) {
            first = new Date().getTime();
            api.toast({
                msg: '再按一次回到桌面',
                duration: 1500,
                location: 'bottom'
            });
            setTimeout(function () {
                first = null;
            }, 1500);
        } else {
            if (new Date().getTime() - first < 1500) {
                //回到系统桌面
                api.toLauncher();
            }
        }
    });
}

//关闭窗体
function closeWin() {
    api.closeWin();
}

//打开窗体-无提示
function openToTwo(winname) {
    api.openWin({
        name: winname,
        url: '' + winname + '.html',
        // delay: 300,
        vScrollBarEnabled: false
    });
}

//打开窗体-有提示
function openTo(winname) {
    api.toast({
        msg: '请先登录',
        duration: 2000,
        location: 'bottom'
    });
    api.openWin({
        name: winname,
        url: '' + winname + '.html',
        // delay: 300
    });
}

//打开窗体-判断登录
function openWin(name) {
    getStorageAll();
    if (!user_id) {
        api.openWin({
            name: 'login_win',
            url: 'login_win.html',
            // delay: 300
        })
    } else {
        api.openWin({
            name: '' + name + '',
            url: '' + name + '.html',
            // delay: 300
        })
    }
}

//切换帐号
function changeAccount() {
    $api.clearStorage();
    api.sendEvent({
        name: 'reGetMyInfo',
        extra: {
            key: 'true'
        }
    });
    api.openWin({
        name: 'login_win',
        url: 'login_win.html',
        // delay: 300
    })
}

//清除缓存
function clearCache() {
    api.clearCache();
    api.toast({
        msg: '清除成功',
        duration: 2000,
        location: 'bottom'
    });
}

function ajaxRequest(url, method, datas, callBack) {
    if (api.connectionType == 'none') {
        api.toast({
            msg: '当前网络不可用，请检查网络配置'
        });
    } else {
        var now = Date.now();
        api.ajax({
            url: serverUrl + url,
            method: method,
            cache: false,
            timeout: 60,
            dataType: 'json',
            data: {
                values: datas
            }
        }, function (ret, err) {
            callBack(ret, err);
        });
    }
}

function getLocation(callBack) {
    var baiduLocation = api.require('baiduLocation');
    baiduLocation.startLocation({
        accuracy: '500m',
        filter: 1,
        autoStop: true
    }, function (ret, err) {
        var sta = ret.status;
        var lat = ret.latitude;
        var lon = ret.longitude;
        var location = '' + lat + ',' + lon + '';
        var ak = '4880fdc9318f40e4afac92629b9bbb66';
        api.ajax({
            url: 'http://api.map.baidu.com/geocoder/v2/?ak=' + ak + '&location=' + location + '&output=json&pois=0',
            method: 'get',
            timeout: 60,
            dataType: 'json',
            data: {}
        }, function (ret, err) {
            //if (ret.status == 0) {
            //	var address = ret.result.formatted_address;
            //}
            callBack(ret, err);
        });
    })
}

function showLoading(time) {
    var body = $api.dom("body");
    var loading = $api.byId("loading");
    if (!loading) {
        $api.append(body, '<div class="aui-loading" id="loading"></div>');
        if (time && time > 0) {
            //如果有时间传进来就定时隐藏
            $api.remove(loading);
        }
    }
}

function hideLoading() {
    var loading = $api.byId("loading");
    setTimeout(function () {
        $api.remove(loading);
    }, 500);

}

//BMAP获取地理位置
function updateLocation() {
    //更新位置信息
    var map = api.require('bMap');
    map.getLocation({
        accuracy: '100m',
        autoStop: true,
        filter: 1
    }, function (ret, err) {
        if (ret.status) {
            var data = {};
            var lat = ret.lat;
            var lon = ret.lon;
            //更新缓存
            $api.setStorage('lat', '' + lat + '');
            $api.setStorage('lon', '' + lon + '');
            data['lat'] = lat;
            data['lon'] = lon;
            data['user_id'] = $api.getStorage('user_id');
            var url = 'user_ajax.ashx?action=updateLocation';
            ajaxRequest(url, 'post', data, function (ret, err) {
                //alert(JSON.stringify(ret.msg));
            });
        } else {
            alert(err.code);
        }
    })
}

function formatDate(time) {
    //var newTime = time.substring(0,10);
    var date = new Date(time * 1000);
    var hour = date.getHours();
    var minute = date.getMinutes();
    var second = date.getSeconds();
    return hour + ':' + minute;
}


function openPicker(dateType) {
    var dateType = $api.byId('' + dateType + '');
    if (api.systemType == 'android') {
        api.openPicker({
            type: 'date',
            title: '选择时间'
        }, function (ret, err) {
            var year = ret.year;
            var month = ret.month;
            var day = ret.day;
            var value1 = year + '-' + month + '-' + day;
            $api.val(dateType, '' + value1 + '');
        });
    } else if (api.systemType == 'ios') {
        api.openPicker({
            type: 'date_time',
            title: '选择时间'
        }, function (ret, err) {
            var year = ret.year;
            var month = ret.month;
            var day = ret.day;
            var hour = ret.hour;
            var minute = ret.minute;
            var value1 = year + '-' + month + '-' + day;
            $api.val(dateType, '' + value1 + '');
        });
    }
}

//微信支付接口
function wxpay(subject, body, amount, tradeNO) {
    var wxPay = api.require('wxPay');
    wxPay.config({
        apiKey: 'wxdbe76a72b62982ed',
        mchId: '1354204002',
        partnerKey: '38jfjksfu8kk3jdjfdjf3jkdjf34jjfd',
        notifyUrl: 'http://riyu.21dianshang.com/tools/weixinpay/return_url.aspx'
    }, function (ret, err) {
        if (ret.status) {
            //alert("配置成功！" + err.code);
            wxPay.pay({
                description: subject, //简要描述
                totalFee: amount,     //订单金额
                tradeNo: tradeNO,     //订单编号
                detail: body,         //明细列表
                feeType: 'CNY'
            }, function (ret, err) {
                if (ret.status) {
                    api.toast({
                        msg: '支付成功',
                        location: 'middle'
                    });
                    sendReGetMyInfo();
                    notify_url(tradeNO);
                } else {
                    //alert("error" + err.code);
                    //alert("msg:" + err.msg);
                    api.toast({
                        msg: '支付失败',
                        location: 'middle'
                    })
                }
            })
        } else {
            //alert("配置失败 error" + err.code);
        }
    })
}

//支付宝接口
function aliPay(subject, body, amount, tradeNO) {
    var obj = api.require('aliPay');
    obj.pay({
        partner: '2017010604892187',
        seller: '1546708912@qq.com',
        rsaPriKey: 'MIICXQIBAAKBgQDcu4jUmoUIiMW0ok0MJXTDEwH5RbD//urafQ59d+MLLRMWOnEy2MjamTqvO3GQTskbr9Z90DVDSXIK2aAFGgi773IFwtdWX10U2N1EYdRw2Paua79Z6Hy0ENWALoBrtePWFbu376EPc/xzDXRZ7YG9goqcLX0AD6jMRu+pkPbpSwIDAQABAoGBANBDlV/bh0e9HKVJOV8LfDaOmZ8jVVTEpbyOn/xcAHnMBqVDcQjjp+cxCkDJ2mWpIHEiIEPHDmo1Qwffu+70WGWRMQKO9lWYWifmhNFhy51uG5aZGTwsUxDQx45yoZfSB9aPJAzlzMz/BewQ3xVMpiPL9CGbkrOQNtuqO6MuBr+RAkEA9nSSREjE0EocCqV1RcvXYcq+orBk9Qmiz/n/k5u3DIafgoaPLDRLKeaiN0rbTJ7aZaemORb6V4w2Gys01Q+PQwJBAOVH8KGytosSW6332punoEsprno2PIvzjaM9c2wfgUXPS0Ex43BZBQHkMElJuWbXSO7O4AN96wuRtphwNmk8SVkCQQCOvUM9ozvCOzn0fJHoY8AR1oAE7875EKSoee2pSyWAbrQRv+dKPdtOoFJRXdyXiuWIvMmMBR/m9sEbiTGnOMTLAkAP2D3f3srQp48gYZ2A3j+skg/VsEPU5Broqgl88lxrp5yqv7jY/b3j2JIhrm+alMwcfL1sYFpK7WHx/Oc1tI3ZAkBwGvpWU5OJt92J3WYBLDLHL8aVW824ja/O2gSstTiR440NY0W55FlVyRv+x7ghX5WP13z6qfhhHI29ieRDrNLa',
        rsaPubKey: 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDcu4jUmoUIiMW0ok0MJXTDEwH5RbD//urafQ59d+MLLRMWOnEy2MjamTqvO3GQTskbr9Z90DVDSXIK2aAFGgi773IFwtdWX10U2N1EYdRw2Paua79Z6Hy0ENWALoBrtePWFbu376EPc/xzDXRZ7YG9goqcLX0AD6jMRu+pkPbpSwIDAQAB',
        subject: subject, //订单名
        body: body, //订单描述
        amount: amount, //金额
        tradeNO: tradeNO, //订单编号
        notifyURL: serverUrl + 'http://fqfm.21dianshang.com/tools/alipayapp/notify_url.aspx'
    }, function (ret, err) {
        if (ret.code == 9000) {
            sendReGetMyInfo();
            notify_url(tradeNO);
            //api.closeToWin({
            //	name : 'root',
            //	animation : {
            //		type : 'flip',
            //		subType : 'from_bottom',
            //		duration : 500
            //	}
            //})
        }
    });
}

//9000：支付成功
//4000：系统异常
//4001：数据格式不正确
//4003：该用户绑定的支付宝账户被冻结或不允许支付
//4004：该用户已解除绑定
//4005：绑定失败或没有绑定
//4006：订单支付失败
//4010：重新绑定账户
//6000：支付服务正在进行升级操作
//6001：用户中途取消支付操作
//0001：缺少商户配置信息（商户id，支付公钥，支付密钥）
//0002：缺少参数（subject、body、amount、tradeNO）
//0003：签名错误（公钥私钥错误）

//支付回调
function notify_url(tradeNO) {
    var url = 'user_ajax.ashx?action=notify_url';
    var data = {};
    data['order_no'] = tradeNO;
    ajaxRequest(url, 'post', data, function (ret, err) {
        // alert(JSON.stringify(ret));
        //关闭到指定窗口，最上面显示的窗口到指定name窗口间的所有窗口都会被关闭
        api.closeToWin({
            name: 'root',
            animation: {
                type: 'flip',
                subType: 'from_bottom',
                duration: 500
            }
        });
    })
}

/******************add by Moqin*********/

/**
 * 添加到localStorage
 * @param storageName名字
 * @param value值
 */
function setLocalStorage(storageName, value) {
    var valueText = localStorage.getItem(storageName);
    if (valueText == null) {
        valueText = value + ",";
    } else {
        valueText += value + ",";
    }
    localStorage.setItem(storageName, valueText)
//            localStorage.removeItem('searchHisroty')
}
/**
 * 获取localstorage,返回一个数组
 * @param storageName名字
 * @returns {*}
 */
function getLocalStorage(storageName, splitText) {
    if (typeof splitText == 'undefined')
        splitText = ","
    var values = localStorage.getItem(storageName);
    if (values == null) {
        return false;
    } else {
        var valueArray = new Array();
        valueArray = values.split(splitText);
        // valueArray=valueArray.trim(valueArray);
        for (var p in valueArray) {
            if (valueArray[p] == 'null' || valueArray[p] == '' || valueArray[p].length == 0) {
                valueArray.splice(p, 1)
            }
        }
        return valueArray;

    }
}
// 字符串变成数组
function toArray(text, splitValue) {
    // alert(text)
    var valueArray = new Array();
    if (typeof splitValue == 'undefined')
        splitValue = ","
    valueArray = text.split(splitValue);
    // valueArray=valueArray.trim(valueArray);
    for (var p in valueArray) {
        if (valueArray[p] == 'null' || valueArray[p] == '' || valueArray[p].length == 0) {
            valueArray.splice(p, 1)
        }
    }
    return valueArray;
}
/**
 * 清除localstorage,参数为空表示清除所有的
 * @param storageName名字
 */
function clearStorage(storageName) {
    if (typeof(storageName) != 'undifined') {
        localStorage.removeItem(storageName);
    } else {
        localStorage.clear();
    }
}
//把时间戳转成时间个2016-12-30 14:36:01 格式
function stampToTime(stamp) {
    if (stamp.indexOf("-") < 0) {
        var newDate = new Date();
        newDate.setTime(stamp * 1000);
        var Y = newDate.getFullYear() + "-";
        var M = newDate.getMonth() + 1 < 10 ? "0" + (newDate.getMonth() + 1) + "-" : (newDate.getMonth() + 1) + "-";
        var D = newDate.getDate() + " ";
        var h = newDate.getHours() + ":";
        var m = newDate.getMinutes() + ":";
        var s = newDate.getSeconds();
        return (Y + M + D + h + m + s);
    } else {
        return stamp;
    }
}
//其他页面跳转到首页
function goToHome(index) {
    api.closeToWin({
        name: 'root'
    });
    api.execScript({
        name: "root",
        script: 'randomSwitchBtnBakHome(' + index + ')'
    })
}
//订单操作，删除取消时候发送监听，更新数据
function updateOrderNum() {
    api.sendEvent({
        name: "updateOrderNum",
        extra: {
            key: 'true'
        }
    })
}
//关闭frame
function closeFrame() {
    api.closeFrame();
}
//检查身份证
function isCarID(NoId) {
    var isNo = false;
    var isIDCard1 = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$/g;//十五位身份证
    var isIDCard2 = /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|(X|x))$/g;//十八位身份证
    if (NoId.length == 15) {
        if (isIDCard1.test(NoId)) {
            isNo = true;
        }
    } else if (NoId.length == 18) {
        if (isIDCard2.test(NoId)) {
            isNo = true;
        }
    }
    return isNo;
}
//跳到聊天http://192.168.3.4/thinkphp/public/index.php/index/User/userInfo/userName/13678970710
//type,有值1表示跟公司聊天
function goToChat(userName,type){
    var data = {};
    url = "User/userInfo/userName/"+userName;
    ajaxRequest(url, 'get', data, function (ret, err) {
        if (ret.status == 1) {
            var chatName,chatImg,chatId;
            if(type){
                chatName=ret.msg.company.company;
                chatImg=ret.msg.company.thumb;
                chatId=ret.msg.userid;
            }else{
                chatName=ret.msg.nickname;
                chatImg=ret.msg.head_portrait;
                chatId=ret.msg.userid;
            }
            openchat(chatId,chatImg,chatName,'../',type);
        } else {
            api.toast({
                msg: '聊天失败，请重试',
                duration: 2000,
                location: 'bottom'
            });
        }
    });
}
//提示失败的关闭,定时1.5s后关闭
function failClose(){
    setTimeout(function () {
        closeWin();
    },1500)
}
//加载滚动玩文字
/**
 *
 * @param speed  速度
 * @param oneHeight  一个行的高度
 */
function textMove(element,speed,oneHeight) {
    setInterval(function () {
        var ulHeight=$(element).height();
        var ulMarginTop=$(element).css("margin-top");
        $(element).animate({"margin-top":"-="+oneHeight+"px"},500,function () {
            if(Math.abs(parseInt(ulMarginTop))>=(ulHeight-oneHeight)){
                $(element).css({"margin-top":"0"})
            }
        })
    },speed);
}\\
//ADDED BY EKIN
//跳转到商家
function go2Shop(companyid, path) {
    path = path ? path : './';
    api.openWin({
        name: 'my/myShop_win',
        url: path + 'my/myShop_win.html',
        pageParam: {
            companyid: companyid
        }
    });
    event.preventDefault();
    event.stopPropagation();
}

function go2User(userid, path) {
    path = path ? path : './';
    api.openWin({
        name: 'my/personInfo_win',
        url: path + 'my/personInfo_win.html',
        pageParam: {
            userid: userid
        }
    });
}

//跳转到商品
function go2Pro(itemid, path) {
    path = path ? path : './';
    api.openWin({
        name: 'proInfo_win',
        url: path + 'proInfo_win.html',
        pageParam: {
            itemid: itemid
        }
    });
}

//聊天
function openchat(userid, avatar, name, path, isCompany,itemid) {
    getStorageAll();
    if (user_id == userid) {
        api.toast({msg: '不能和本人聊天'});
    } else {
        path = path ? path : './';
        api.openWin({
            name: 'chat_win',
            url: path + 'userchat/chat_win.html',
            pageParam: {
                targetUserId: userid,
                targetUserAvatar: avatar,
                targetUsername: name,
                isCompany: isCompany,
                itemid:itemid
            }
        });
    }
}
//检查某用户id是否有新信息
function hasNewMsgByUid(targetUserId) {
    var chatContent = $api.getStorage('chatContent');
    if (chatContent) {
        var hasNew = false;
        for (i in chatContent) {
            if (chatContent[i].senderUserId == targetUserId && chatContent[i].unreadCount > 0) {
                hasNew = true;
                break;
            }
        }
        return hasNew;
    }
}

//显示最近时间
function formatMsgTime(timespan) {

    var dateTime = new Date(timespan * 1000);

    var year = dateTime.getFullYear();
    var month = dateTime.getMonth() + 1;
    var day = dateTime.getDate();
    var hour = dateTime.getHours();
    var minute = dateTime.getMinutes();
    var second = dateTime.getSeconds();
    var now = new Date();
    var now_new = Date.parse(now.toDateString());  //typescript转换写法

    var milliseconds = 0;
    var timeSpanStr;

    milliseconds = now_new - timespan;

    if (milliseconds <= 1000 * 60 * 1) {
        timeSpanStr = '刚刚';
    }
    else if (1000 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60) {
        timeSpanStr = Math.round((milliseconds / (1000 * 60))) + '分钟前';
    }
    else if (1000 * 60 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24) {
        timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60)) + '小时前';
    }
    else if (1000 * 60 * 60 * 24 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24 * 15) {
        timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60 * 24)) + '天前';
    }
    else if (milliseconds > 1000 * 60 * 60 * 24 * 15 && year == now.getFullYear()) {
        timeSpanStr = month + '月' + day + '日 ' + hour + ':' + minute;
    } else {
        timeSpanStr = year + '年' + month + '月' + day + '日 ' + hour + '时';
    }
    return timeSpanStr;
};

function GetFileName(url){
    return url.replace('http://','');
    // return url.substring(url.lastIndexOf('/')+1);
}

function iCache(selector) {
        selector.each(function(data) {
                //msg(data);
                ! function(data) {
                        var url = selector.eq(data).attr("src");
                        var img = this;
                        var filename = GetFileName(url);
                        var path = "cache://" + filename;
                        var obj = api.require('fs');
                        obj.exist({
                                path : path
                        }, function(ret, err) {
                                //msg(ret);
                                if (ret.exist) {
                                        if (ret.directory) {
                                                //api.alert({msg:'该路径指向一个文件夹'});
                                        } else {
                                                //api.alert({msg:'该路径指向一个文件'});
                                                //selector.eq(data).src=path;
                                                selector.eq(data).attr('src', null);
                                                path = api.cacheDir + '/' + filename;
                                                selector.eq(data).attr('src', path);
                                                // alert(selector.eq(data).attr("src"));
                                        }
                                } else {
                                        api.download({
                                                url : url,
                                                savePath : path,
                                                report : false,
                                                cache : true,
                                                allowResume : true
                                        }, function(ret, err) {
                                                //msg(ret);
                                                if (ret) {
                                                        var value = ('文件大小：' + ret.fileSize + '；下载进度：' + ret.percent + '；下载状态' + ret.state + '存储路径: ' + ret.savePath);
                                                } else {
                                                        var value = err.msg;
                                                };
                                        });
                                }
                        });
                }(data);
        });
};
